import { Component, ViewChild } from '@angular/core';
import { Platform, ToastController, MenuController, Nav } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { AppMinimize } from '@ionic-native/app-minimize';

import { UserService } from "../providers/UserService";
import { StorageService } from "../providers/StorageService";

import { HomePage } from '../pages/home/home';
import { LoginPage } from '../pages/login/login';

@Component({
  templateUrl: 'app.html',
  providers: [UserService, AppMinimize]
})
export class MyApp {
  rootPage: any;
  backButtonPressed: boolean = false; //用于判断返回键是否触发
  @ViewChild(Nav) nav: Nav;
  pages: Array<{ title: string, component: any }>;

  constructor(
    statusBar: StatusBar,
    splashScreen: SplashScreen,
    public platform: Platform,
    public toastCtrl: ToastController,
    public menuCtrl: MenuController,
    private userService: UserService,
    private storageService: StorageService,
    private appMinimize: AppMinimize
  ) {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();

      this.registerBackButtonAction(); //注册返回按键事件

      if (localStorage.getItem('user_token')) {
        this.userService.isLogin({'user_token': localStorage.getItem('user_token')}).then(data => {
          if (data.status == 200) {
            this.menuCtrl.enable(true, 'slideMenu');
            this.storageService.write('UserInfo', data.user);
            this.rootPage = HomePage;
          } else {
            localStorage.clear();
          }
        });
      } else {
        this.rootPage = LoginPage
      }
    });
  }

  registerBackButtonAction() {
    this.platform.registerBackButtonAction(() => {
      this.appMinimize.minimize();
    });
  }
}
